<template>
	<transition name="mj-message-fade" @after-leave="handAfterLeave">
		<div :class="classes" v-show="visible" :style="`top:${topOffset}px`">
            <Icon :type="`${type}-filling`" :class="`my-message-icon-${this.type}`"></Icon> 
            <span class="my-message-text">{{msg}}</span>
            <Icon type="close" class="my-message-close" v-if="showClose" @click.native="close"></Icon> 
        </div>
	</transition>
</template>

<script>
    import './message.css'
	export default {
		name: 'CustomMessage',
		data() {
			return {
				msg: '',
				duration: 3000,
				visible: false,
				topOffset: 20,
				onClose: null,
				type: 'success',
                showClose: false,
                background: false
			}
		},
        computed:{
            classes() {
                return [
                    'custom-message',
                    {
                        [`my-message-${this.type}`]: this.background
                    }
                ];
            }
        },
		mounted() {
            this.closeMsg()
            document.addEventListener('keydown', this.keydown);
		},
		methods: {
			// 过度动画结束时销毁和移除当前节点dom
			handAfterLeave(){
				this.$destroy(true)
				this.$el.parentNode.removeChild(this.$el)
			},
			// 设置定时器 关闭消息
			closeMsg() {
				if(this.duration > 0) {
                    this.timer = setTimeout(() => {
                        this.close()
                        clearTimeout(this.timer)
                    }, this.duration)
                }
			},
			// 设置关闭时触发的关闭回调函数
			close() {
                this.visible = false
				if(typeof this.onClose==='function'){
				    this.onClose(this)
				}
			},
            keydown(e) {
                if (e.keyCode === 27) { // esc关闭消息
                    if (!this.visible) {
                        this.close();
                    }
                }
            }
		},
        beforeDestroy() {
            document.removeEventListener('keydown', this.keydown);
        }
	}
</script>

